package com.youlu.campus.service.item;

import com.mongodb.client.result.DeleteResult;

import com.youlu.campus.entity.UserLikeItem;
import com.youlu.campus.entity.UserPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserLikeItemService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String USER_ITEM_LIKE = "campus:item:like:%s:%s";

    /**
     * 用户对文创商品点赞
     *
     * @param itemId
     * @param currentUser
     * @param optionType  操作类型 1 喜欢 2、不喜欢
     */
    public void like(String itemId, UserPO currentUser, Integer optionType) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currentUser.getId()));
        query.addCriteria(Criteria.where("itemId").is(itemId));
        Update update = new Update();
        Date now = new Date();
        boolean exists = this.mongoTemplate.exists(query, UserLikeItem.class);
    }

    public UserLikeItem find(String appId, String platform, String userId,
                             String itemId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("itemId").is(itemId));
        query.addCriteria(Criteria.where("appId").is(appId));
        query.addCriteria(Criteria.where("platform").is(platform));
        return mongoTemplate.findOne(query, UserLikeItem.class);
    }

    public boolean create(UserLikeItem req) {
        try {
            req.setId(null);
            req.setCreatedTime(new Date());
            req = mongoTemplate.insert(req);
            if (StringUtils.isNotBlank(req.getId())) {
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error(":>>> 新增用户收藏商品记录错误:{}", e);
            return false;
        }

    }

    public boolean delete(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        DeleteResult result = mongoTemplate.remove(query, UserLikeItem.class);
        return result.getDeletedCount() > 0 ? true : false;
    }
}
